package com.freecloud.whispered.auth.oauth2;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.freecloud.framework.config.ClientConfig;
import com.freecloud.framework.constant.Constant;
import com.freecloud.framework.request.R;
import com.freecloud.framework.utils.DESUtils;
import com.freecloud.framework.utils.HttpContextUtils;
import com.freecloud.framework.utils.SpringContextUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 内部服务调用Token拦截器
 * @Author: maomao
 * @Date: 2019-08-11 19:51
 */
public class ClientOAuth2Filter extends AuthenticatingFilter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //从header中获取token
        String token = getRequestToken((HttpServletRequest)request);
        if(StrUtil.isBlank(token)){
            return null;
        }
        return new ClientOAuth2Token(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        if(StrUtil.isBlank(token)){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());

            logger.error("ClientOAuth2Filter ERROR");

            String json = JSONUtil.toJsonStr(R.error(HttpStatus.HTTP_UNAUTHORIZED, "invalid client token"));
            httpResponse.getWriter().print(json);
            return false;
        }

        return executeLogin(request, response);
    }


    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){

        ClientConfig clientConfig = SpringContextUtils.getBean(ClientConfig.class);
        //从header中获取token
        String token = httpRequest.getHeader(clientConfig.getClientTokenHeader());

        return token;
    }
}
